/*
    3D Office Environment
    Copyright (C) 2011  Till Merker

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.

*/

#include "DotSceneOfficeScene.h"
#include "DotSceneLoader.h"
#include <Plugins/OctreeSceneManager/OgreOctreePlugin.h>

namespace OfficeEnv {

SceneManager* DotSceneOfficeScene::createSceneManager() {    
    mRoot->installPlugin(new OctreePlugin());
    return mRoot->createSceneManager(ST_GENERIC);
}

void DotSceneOfficeScene::loadScene(String sceneFile) {
    DotSceneLoader loader;
    loader.parseDotScene(sceneFile, "General", mSceneMgr);
    
    mCamera = mSceneMgr->getCamera("Camera");
    mCamera->setAspectRatio((float) mWidth / mHeight);    
    mCamera->setNearClipDistance(5);
    
    if(mCamera->getParentSceneNode() != mSceneMgr->getRootSceneNode()) {
	/* If the camera is attached to a node, take this node's position and orientation to the camera */
	mCamera->setOrientation(mCamera->getRealOrientation());
	mCamera->setPosition(mCamera->getRealPosition());
	mCamera->getParentSceneNode()->setPosition(Vector3::ZERO);
	mCamera->getParentSceneNode()->setOrientation(Quaternion::IDENTITY);
    }
    
    mY = mCamera->getPosition().y;
}

void DotSceneOfficeScene::getDesktopEntity(int desktopIndex, SceneNode **node, Entity **entity) {
	char entName[16];
	char matName[16];
	snprintf((char*)&entName, 16, "DeskEnt%i", desktopIndex);
	snprintf((char*)&matName, 16, "DeskMat%i", desktopIndex);
	
	*entity = mSceneMgr->getEntity(entName);
	*node = (*entity)->getParentSceneNode();	
	
	/* Recreate entity - attaching the material doesn't work otherwise (TODO: why not?) */
	mSceneMgr->destroyEntity(*entity);
	*entity = mSceneMgr->createEntity(entName, "DeskMesh");
	(*node)->attachObject(*entity);
	
	(*entity)->setMaterialName(matName);
}

Vector3 DotSceneOfficeScene::getUpVector() {
    return Vector3::UNIT_Y;
}

void DotSceneOfficeScene::getPitchLimits(Radian &minPitch, Radian &maxPitch) {    
    minPitch = Degree(-90);
    maxPitch = Degree(90);  
}

void DotSceneOfficeScene::moveTo(Vector3 dest) {
    
    /* Collision detection not implemented yet*/
    
    glueToGround(dest);  
    mCamera->setPosition(dest);   
        
}

void DotSceneOfficeScene::glueToGround(Vector3 &pos) {
    /* Not implemented yet - just float at original height */
    pos.y = mY;
}

}